/**
 * 步骤6测试：选择时段（onClickDate -> 时段页 -> onClickTimeslot）
 */

import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'
import { HttpSession } from '../src/main/request/http-session'
import { getPageParser } from '../src/main/automation/page-parser'
import { loadConfig } from '../src/main/config/index'
import { setupLogger } from '../src/main/logger/index'
import { writeFile, mkdir, readFile } from 'node:fs/promises'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const projectRoot = join(__dirname, '..')

const BASE_URL = 'https://abs1.td.gov.hk/tdab2/tdabs_external/AdminServlet_tchinese'
const SNAPSHOT_DIR = join(projectRoot, 'test-steps-snapshots')

async function saveSnapshot(name: string, html: string, metadata: any = {}) {
  await mkdir(SNAPSHOT_DIR, { recursive: true })
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
  const filename = `${timestamp}_step06_${name}.html`
  const filepath = join(SNAPSHOT_DIR, filename)
  await writeFile(filepath, html, 'utf8')
  console.log(`  ✓ 快照已保存: ${filename}`)
  return filepath
}

async function loadStep5Result() {
  const files = await import('node:fs/promises')
  const dir = await files.readdir(SNAPSHOT_DIR)
  const step5Files = dir.filter(f => f.includes('step05_calendar') && f.endsWith('.html')).sort().reverse()
  
  if (step5Files.length === 0) {
    throw new Error('未找到步骤5的快照文件，请先运行步骤5测试')
  }
  
  const latestFile = join(SNAPSHOT_DIR, step5Files[0])
  const html = await readFile(latestFile, 'utf8')
  const parser = getPageParser()
  const formFields = parser.extractFormFields(html, 'frmAppointment')
  const datesResult = parser.parseAvailableDates(html)
  
  return { html, formFields, datesResult, filepath: latestFile }
}

function checkTimeslotPage(html: string): { success: boolean, details: Record<string, boolean>, timeslots: any[] } {
  const parser = getPageParser()
  const timeslotsResult = parser.parseAvailableTimeslots(html)
  const timeslots = timeslotsResult.success && timeslotsResult.data ? timeslotsResult.data : []
  
  const checks = {
    isTimeslotPage: html.includes('cmdGetTimeslotListAction') || html.includes('onClickTimeslot'),
    hasTimeslotLinks: html.includes('onClickTimeslot') || html.includes('redlink'),
    hasForm: html.includes('form') && html.includes('frmAppointment'),
    hasAvailableTimeslots: timeslots.length > 0,
  }
  
  console.log(`\n📄 时段页面检查`)
  console.log('─'.repeat(60))
  for (const [key, value] of Object.entries(checks)) {
    const icon = value ? '✓' : '✗'
    const label = key.replace(/([A-Z])/g, ' $1').trim()
    console.log(`  ${icon} ${label}`)
  }
  
  console.log(`\n  🕐 可用时段数量: ${timeslots.length}`)
  if (timeslots.length > 0) {
    console.log(`  🕐 可用时段:`)
    timeslots.slice(0, 5).forEach((ts, i) => {
      console.log(`    ${i + 1}. ${ts.display_time} (${ts.start_time}-${ts.end_time})`)
    })
    if (timeslots.length > 5) console.log(`    ...`)
  }
  
  return { success: checks.isTimeslotPage && checks.hasForm, details: checks, timeslots }
}

async function testStep6() {
  console.log('步骤6测试：选择时段（onClickDate -> 时段页 -> onClickTimeslot）')
  console.log('='.repeat(60))
  
  await loadConfig()
  await setupLogger()
  
  // 加载步骤5的结果
  console.log('\n📂 加载步骤5结果...')
  const step5Result = await loadStep5Result()
  const step5Fields = step5Result.formFields.success && step5Result.formFields.data ? step5Result.formFields.data : {}
  const availableDates = step5Result.datesResult.success && step5Result.datesResult.data ? step5Result.datesResult.data : []
  
  console.log(`  从步骤5提取字段数: ${Object.keys(step5Fields).length}`)
  console.log(`  可用日期数量: ${availableDates.length}`)
  
  if (availableDates.length === 0) {
    console.log('\n❌ 步骤6失败：没有可用日期，无法选择时段')
    process.exit(1)
  }
  
  const session = new HttpSession()
  
  // 子步骤6.1: 选择第一个可用日期（调用onClickDate -> cmdGetTimeslotListAction）
  console.log('\n子步骤6.1: 选择日期（onClickDate -> cmdGetTimeslotListAction）')
  console.log('─'.repeat(60))
  
  const selectedDate = availableDates[0]
  console.log(`  选择日期: ${selectedDate}`)
  
  const payload1: Record<string, string> = {
    ...step5Fields,
    storedAppointmentOperation: 'A',
    storedAppointmentTimeslotDate: selectedDate,
    timestamp: Date.now().toString(),
  }
  
  const url1 = `${BASE_URL}?cmd=cmdGetTimeslotListAction`
  console.log(`请求: POST ${url1}`)
  console.log(`  载荷字段数: ${Object.keys(payload1).length}`)
  
  const response1 = await session.postForm(url1, payload1, `${BASE_URL}?cmd=cmdGetCalendarAction`)
  const check1 = checkTimeslotPage(response1.body)
  
  await saveSnapshot('timeslot_list', response1.body, {
    step: '6.1',
    url: response1.url,
    status: response1.status,
    check: check1,
    selectedDate,
    availableTimeslots: check1.timeslots.length,
  })
  
  if (!check1.success || check1.timeslots.length === 0) {
    console.log('\n❌ 子步骤6.1失败：未找到可用时段')
    process.exit(1)
  }
  
  // 子步骤6.2: 选择第一个可用时段（调用onClickTimeslot -> cmdConfirmAppointment）
  console.log('\n子步骤6.2: 选择时段（onClickTimeslot -> cmdConfirmAppointment）')
  console.log('─'.repeat(60))
  
  const selectedTimeslot = check1.timeslots[0]
  console.log(`  选择时段: ${selectedTimeslot.display_time} (${selectedTimeslot.start_time}-${selectedTimeslot.end_time})`)
  console.log(`  时段ID: ${selectedTimeslot.id}`)
  
  const parser = getPageParser()
  const timeslotFields = parser.extractFormFields(response1.body, 'frmAppointment')
  const timeslotFieldsData = timeslotFields.success && timeslotFields.data ? timeslotFields.data : {}
  
  const payload2: Record<string, string> = {
    ...timeslotFieldsData,
    storedAppointmentOperation: 'A',
    storedAppointmentTimeslotId: selectedTimeslot.id,
    storedAppointmentTimeslotFromTime: selectedTimeslot.start_time,
    storedAppointmentTimeslotToTime: selectedTimeslot.end_time,
    timestamp: Date.now().toString(),
  }
  
  const url2 = `${BASE_URL}?cmd=cmdConfirmAppointment`
  console.log(`请求: POST ${url2}`)
  console.log(`  载荷字段数: ${Object.keys(payload2).length}`)
  
  const response2 = await session.postForm(url2, payload2, response1.url)
  
  // 检查确认页面
  const isConfirmPage = response2.body.includes('cmdConfirmAppointment') || response2.body.includes('確認') || response2.body.includes('确认')
  
  console.log(`\n📄 确认页面检查`)
  console.log('─'.repeat(60))
  console.log(`  ${isConfirmPage ? '✓' : '✗'} 是确认页面`)
  
  await saveSnapshot('confirm', response2.body, {
    step: '6.2',
    url: response2.url,
    status: response2.status,
    isConfirmPage,
    selectedDate,
    selectedTimeslot: {
      id: selectedTimeslot.id,
      time: selectedTimeslot.display_time,
      from: selectedTimeslot.start_time,
      to: selectedTimeslot.end_time,
    },
  })
  
  if (!isConfirmPage) {
    console.log('\n❌ 子步骤6.2失败：未到达确认页面')
    process.exit(1)
  }
  
  console.log('\n✓ 步骤6成功：已选择时段并到达确认页面')
  console.log(`\n📁 快照目录: ${SNAPSHOT_DIR}`)
}

testStep6().catch((error) => {
  console.error('\n❌ 测试失败:', error)
  process.exit(1)
})

